package spjm.pt.pmartins.racelogger;

import java.util.ArrayList;

import pt.spjm.pmartins.lapcounter.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

public class Setup_Pilots_Edit extends Activity {

	private EditText pName;
	private EditText pNumber;
	private Obj_CurrentData cData;
	private int id;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.setup_pilots_add);
		
		pName = (EditText) findViewById(R.id.newPilotName);
		pNumber = (EditText) findViewById(R.id.newPilotNumber);
		
		cData = LapCounter.cData;
		
		Bundle bundle = this.getIntent().getExtras();
		id = bundle.getInt("id");
	
		pName.setText(cData.getPilots().get(id).getName());
		pNumber.setText(cData.getPilots().get(id).getNumber()+"");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return true;
	}
	
	public void onNewPilotSaveBtn(View v){
		String name;
		int number;
		
		try {
			name = pName.getText().toString();
			number = Integer.parseInt(pNumber.getText().toString());

			if (name.equals("") || number < 1) {
				throw new IllegalArgumentException();
			}

			if (cData.getPilots() == null) {
				cData.setPilots( new ArrayList<Obj_Pilot>() );
			}

			cData.getPilots().get(id).setName(name);
			cData.getPilots().get(id).setNumber(number);
			
			 Intent returnIntent = new Intent();
			 setResult(RESULT_OK, returnIntent);     
			 finish();

		} catch (Exception e) {
			showDialogMsg(R.string.invalid_data, false);
		}		
	}
	
	public void showDialogMsg(final int msg, final boolean resetData) {
		AlertDialog.Builder bdialog;
		bdialog = new AlertDialog.Builder(this);
		bdialog.setTitle("");
		bdialog.setMessage(msg);
		bdialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				//if(resetData){
				//	pName.setText("");
				//	pNumber.setText("");
				//}
				
				finish();
			}
		});
		AlertDialog dialog = bdialog.create();
		dialog.show();
	}
}
